package com.hyg.ndkapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.hyg.ndkapplication.data.SeriCmds;
import com.lyn.serialport.control.ByteUtil;
import com.lyn.serialport.control.SerialPortControler;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: HuangYuGuang
 * Date: 2024/3/7
 */
public class SerialActivity extends AppCompatActivity implements View.OnClickListener{
    private String TAG = "SerialActivity";

    private SerialPortControler serialPort0_Controler;
    private String serialPort1 = "/dev/ttyXRUSB2";

    private volatile boolean isStart = false;
    private volatile List<byte[]> cmds = new ArrayList<>();

    private TextView tv_seri;
    private CheckBox cb_16;
    private CheckBox cb_stop;

    public static void launch(Activity from){
        from.startActivity(new Intent(from, SerialActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serial);

        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
        findViewById(R.id.btn3).setOnClickListener(this);
        findViewById(R.id.btn4).setOnClickListener(this);
        findViewById(R.id.btn5).setOnClickListener(this);
        findViewById(R.id.btn6).setOnClickListener(this);
        findViewById(R.id.btn7).setOnClickListener(this);

        tv_seri = findViewById(R.id.tv_seri);
        cb_16 = findViewById(R.id.cb_16);
        cb_stop = findViewById(R.id.cb_stop);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
//            serialPort0_Controler = new SerialPortControler(serialPort1, 19200, 0);
            serialPort0_Controler = new SerialPortControler(serialPort1, 9600, 0);
            Log.d(TAG,"serialPort0_Controler = "+serialPort0_Controler);
            tv_seri.setText(serialPort1 + " serialPort0_Controler = "+serialPort0_Controler);

            new SendTask().start();
            new ReceivedTask().execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        if (AppUtils.isFastClick()) return;
        switch (v.getId()){
            case R.id.btn1:
                cmds.add(SeriCmds.L_TIME);
                break;
            case R.id.btn2:
                cmds.add(SeriCmds.L_TEMP);
                break;
            case R.id.btn3:
                cmds.add(SeriCmds.L_GEAR);
                break;
            case R.id.btn4:
                cmds.add(SeriCmds.L_ON1);
                break;
            case R.id.btn5:
                cmds.add(SeriCmds.L_ON2);
//                cmds.add(SerialPortUtil.getCMD((byte)0x03,(byte)0x00,(byte)0x00));
                break;
            case R.id.btn6:
                cmds.add(SeriCmds.L_OFF);
//                cmds.add(SerialPortUtil.getCMD((byte)0x03,(byte)0x01,(byte)0x01));
                break;
            case R.id.btn7:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        isStart = false;
        super.onDestroy();
    }

    private void addTestLog(boolean isSend, String msg){
        String tag = isSend?"-->":"<--";
        if(tv_seri.getLineCount() > 300){
            tv_seri.setText(String.format("%s %s\n", tag, msg));
        }else {
            tv_seri.append(String.format("%s %s\n", tag, msg));
        }
    }

    class SendTask extends Thread{
        @Override
        public void run() {
            isStart = true;
            while (isStart){
                try {
                    if(cmds.size() > 0){
                        byte[] cmd = cmds.remove(0);
                        serialPort0_Controler.sendCMDSInThread(cmd);
                        SerialActivity.this.runOnUiThread(() -> addTestLog(true,ByteUtil.bytes2hex(cmd).trim()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                SystemClock.sleep(500);
            }
        }
    }

    class ReceivedTask extends AsyncTask<String,String,String>{

        @Override
        protected void onProgressUpdate(String... values) {
            if(!cb_stop.isChecked()){
                addTestLog(false, values[0]);
            }
        }

        @Override
        protected String doInBackground(String... strings) {
            isStart = true;
            while (isStart){
                try {
                    byte[] bytes = serialPort0_Controler.readData();
                    publishProgress(cb_16.isChecked()?ByteUtil.bytes2hex(bytes).trim():ByteUtil.bytes2String(bytes));
                } catch (Exception e) {
                    e.printStackTrace();
                    publishProgress(e.getMessage());
                }
                SystemClock.sleep(200);
            }
            return "";
        }
    }

    private void showOnUIThread(String msg){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showConfirmDialog(msg);
            }
        });
    }

    private void showConfirmDialog(String str){
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage(str);
        dialog.show();
    }
}
